package com.cc.cbdb.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.cc.cbdb.R;
import com.cc.cbdb.adapter.DataListAdapter;
import com.cc.cbdb.common.constants.Constant;
import com.cc.cbdb.common.report.ReportHelper;
import com.cc.cbdb.common.utils.NetRequest;
import com.cc.cbdb.common.utils.StringUtil;
import com.cc.cbdb.common.utils.ToastUtil;
import com.cc.cbdb.entity.PageBean;
import com.cc.cbdb.entity.QBiogCustom;
import com.cc.cbdb.view.LoadingDialog;
import com.cc.cbdb.view.searchView.ICallBack;
import com.cc.cbdb.view.searchView.SearchView;
import com.cc.cbdb.view.searchView.bCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Request;

public class SearchActivity extends AppCompatActivity {

    private static final String TAG = "SearchActivity";

    private Context mContext;
    private List<QBiogCustom> mResults = new ArrayList<>();
    private ListView lv_content;
    private TextView tv_page_info,tv_search_count;
    private DataListAdapter adapter;
    private LoadingDialog mLoadingDialog;
    private boolean isLoad = false;
    //当前页码
    private int mPageNum = 1;
    //总页码
    private int mTotalPage;
    //搜索内容
    private String mSearchStr = "";
    private boolean scrollFlag = false; // 标记是否滑动
    private static final int DEFAUT = 0;
    private static final int NEXT_PAGE = 1;  //下一页
    private static final int PRE_PAGE = 2;   //上一页
    private static final int VISIBLE = View.VISIBLE;
    private static final int INVISIBLE = View.INVISIBLE;
    private static final int GONE = View.GONE;
    //其他页面传递过来的请求参数
    private String mTitle = "";
    private String param1,param2,param3;
    private String[] multiParams,singleParams;
    private MsgHandler handler;
    private boolean isSelect;

    private ReportHelper reportHelper;

    private static class MsgHandler extends Handler {
        private WeakReference<SearchActivity> reference;

        MsgHandler(SearchActivity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            SearchActivity activity = reference.get();
            Bundle data = msg.getData();
            if (activity.adapter == null) {
                activity.adapter = new DataListAdapter(activity, activity.mResults);
                activity.adapter.isSelect = activity.isSelect;
                activity.lv_content.setAdapter(activity.adapter);
            } else {
                activity.adapter.notifyDataSetChanged();
                switch (msg.what) {
                    case NEXT_PAGE:
                        //上滑（下一页），条目更新后跳到第一个
                        if (!activity.lv_content.isStackFromBottom()) {
                            activity.lv_content.setStackFromBottom(true);
                        }
                        activity.lv_content.setStackFromBottom(false);
                        break;
                    case PRE_PAGE:
                        //下滑（上一页），条目更新后跳到最后一个
                        if (!activity.lv_content.isStackFromBottom()) {
                            activity.lv_content.setStackFromBottom(false);
                        }
                        activity.lv_content.setStackFromBottom(true);
                        break;
                    case DEFAUT:
                        break;
                }

            }
            activity.mLoadingDialog.dismiss();
            activity.tv_page_info.setText("当前页：" + data.getInt("pageNum") + " 总页数：" + data.getInt("totalPage"));
            activity.tv_search_count.setText("查询到" + data.getInt("totalCount") + "条数据");
            if (activity.tv_page_info.getVisibility() == INVISIBLE || activity.tv_search_count.getVisibility() == INVISIBLE) {
                activity.tv_page_info.setVisibility(VISIBLE);
                activity.tv_search_count.setVisibility(VISIBLE);
            }
            activity.isLoad = false;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        reportHelper = ReportHelper.getInstance(this);
        mContext = this;
        initUI();
    }

    private void initUI() {
        handler = new MsgHandler(this);
        //获取配置页面参数
        Intent intent = getIntent();
        mTitle = intent.getStringExtra("title");
        boolean isShowSeachView = intent.getBooleanExtra("isShowSeachView", true);
        boolean isFromSelected = intent.getBooleanExtra("isFromSelected", false);
        isSelect = intent.getBooleanExtra("isSelect",false);
        String tabName = Constant.SVTAB.SV_NAMES_TAB;
        if (isFromSelected) {
            param1 = intent.getStringExtra("personName");
            param2 = intent.getStringExtra("textName");
            multiParams = intent.getStringArrayExtra("multiParams");
            singleParams = intent.getStringArrayExtra("singleParams");
//            Log.d(TAG,"personName:"+param1+",textName:"+param2);
//            Log.d(TAG,"multiParams:"+ Arrays.toString(multiParams));
//            Log.d(TAG,"singleParams:"+Arrays.toString(singleParams));
        } else {
            tabName = intent.getStringExtra("tabName");
            param1 = intent.getStringExtra("param1");
            param2 = intent.getStringExtra("param2");
            param3 = intent.getStringExtra("param3");
        }

        LoadingDialog.Builder builder = new LoadingDialog.Builder(mContext);
        builder.setMessage("加载中...");
        mLoadingDialog = builder.create();

        //绑定组件
        TextView titleBar = findViewById(R.id.titleBar);
        SearchView searchView = findViewById(R.id.search_view);
        searchView.setTabName(tabName);
        if (tabName != null) {
            searchView.queryData("");
        }
        lv_content = findViewById(R.id.lv_content);
        tv_page_info = findViewById(R.id.tv_page_info);
        tv_search_count = findViewById(R.id.tv_search_count);

        titleBar.setText(mTitle);
        if (!isShowSeachView) {
            searchView.setVisibility(GONE);
            getDataAsync(DEFAUT);
        }
        if (isSelect) {
            getDataAsync(DEFAUT);
        }

        // 设置点击搜索按键后的操作（通过回调接口）
        // 参数 = 搜索框输入的内容
        searchView.setOnClickSearch(new ICallBack() {
            @Override
            public void SearchAciton(String string) {
                if (StringUtil.isEmpty(string)) {
                    ToastUtil.showShort(mContext, "请输入要查询的内容！");
                } else {

                    Log.d(TAG, "搜索的内容为：" + string);

                    mSearchStr = string;
                    //请求后台接口
                    getDataAsync(DEFAUT);
                }
            }
        });

        // 设置点击返回按键后的操作（通过回调接口）
        searchView.setOnClickBack(new bCallBack() {
            @Override
            public void BackAciton() {
                finish();
            }
        });

        // 给listview添加滚动监听
        lv_content.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                    scrollFlag = true;
                } else {
                    scrollFlag = false;
                }

                if (mResults != null) {
                    if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                            && lv_content.getLastVisiblePosition() >= mResults.size() - 1
                            && !isLoad && !scrollFlag) {

                        isLoad = true;

                        //加载下一页数据
                        if (mPageNum < mTotalPage) {
                            mPageNum++;
                            getDataAsync(NEXT_PAGE);
                        } else {
                            ToastUtil.showShort(mContext, "已经到底了~");
                            isLoad = false;
                        }
                    }
                    // 判断滚动到顶部
                    if (lv_content.getChildCount() > 0 && lv_content.getFirstVisiblePosition() == 0
                            && lv_content.getChildAt(0).getTop() >= 0
                            && !isLoad && !scrollFlag) {
                        isLoad = true;
                        //加载上一页数据
                        if (mPageNum > 1) {
                            mPageNum--;
                            getDataAsync(PRE_PAGE);
                        } else {
                            ToastUtil.showShort(mContext, "已经到顶了~");
                            isLoad = false;
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }

        });
    }

    /**
     * 异步请求接口
     *
     * @param mode 翻页模式
     */
    private void getDataAsync(final int mode) {
        mLoadingDialog.show();

        String url = Constant.DOMAIN_PROJECT;
        HashMap<String, String> params = new HashMap<>();
        //根据title来判断请求的接口，设置不同的请求参数
        switch (mTitle) {
            case Constant.TITLE.TITLE_QNAME:
                url += Constant.URL.URL_QNAME;
                params.put("pageNum", mPageNum + "");
                params.put("name", mSearchStr);
                break;
            case Constant.TITLE.TITLE_QBIOGADDR:
                url += Constant.URL.URL_QBIOGADDR;
                params.put("pageNum", mPageNum + "");
                params.put("cAddrId", param1);
                params.put("cAddrTypes", param2);

                reportHelper.reportQueryState(ReportHelper.ADDRESS,param1,null);
                reportHelper.reportQueryState(ReportHelper.ADDRTYPE,param2,null);
                break;
            case Constant.TITLE.TITLE_QBIOGOFF:
                url += Constant.URL.URL_QBIOGOFF;
                params.put("pageNum", mPageNum + "");
                params.put("id", param1);
                params.put("entryId", param2);
                params.put("tempId", param3);

                reportHelper.reportQueryState(ReportHelper.OFFICE,param1,param3);
                reportHelper.reportQueryState(ReportHelper.ENTRYTYPE,param2,null);
                break;
            case Constant.TITLE.TITLE_QADVANCEDQUERY:
                url += Constant.URL.URL_QADVANCEDQUERY;
                params.put("pageNum", mPageNum + "");
                params.put("personName", param1 == null ? "" : param1);
                params.put("textName", param2 == null ? "" : param2);
                if (multiParams != null) {
                    params.put("choronymIds", multiParams[0] == null ? "" : multiParams[0]);
                    params.put("dyIds", multiParams[1] == null ? "" : multiParams[1]);
                    params.put("addrTypeIds", multiParams[2] == null ? "" : multiParams[2]);
                    params.put("appointments", multiParams[3] == null ? "" : multiParams[3]);
                    params.put("offcategoryIds", multiParams[4] == null ? "" : multiParams[4]);
                    params.put("biogInstIds", multiParams[5] == null ? "" : multiParams[5]);
                    params.put("enthnicityIds", multiParams[6] == null ? "" : multiParams[6]);
                    params.put("instIds", multiParams[7] == null ? "" : multiParams[7]);
                    params.put("statusIds", multiParams[8] == null ? "" : multiParams[8]);
                }
                if (singleParams != null) {
                    params.put("femaleId", singleParams[0] == null ? "" : singleParams[0]);
                    params.put("addrId", singleParams[1] == null ? "" : singleParams[1]);
                    params.put("id", singleParams[2] == null ? "" : singleParams[2]);
                    params.put("entryId", singleParams[3] == null ? "" : singleParams[3]);
                    params.put("textRoleId", singleParams[4] == null ? "" : singleParams[4]);
                    params.put("tempId", singleParams[5] == null ? "" : singleParams[5]);
                }

                reportHelper.reportQueryState(ReportHelper.CHORONYM,multiParams[0],null);
                reportHelper.reportQueryState(ReportHelper.DY,multiParams[1],null);
                reportHelper.reportQueryState(ReportHelper.ADDRTYPE,multiParams[2],null);
                reportHelper.reportQueryState(ReportHelper.APPOINTMENT,multiParams[3],null);
                reportHelper.reportQueryState(ReportHelper.BIOGINST,multiParams[5],null);
                reportHelper.reportQueryState(ReportHelper.ENTHNICITY,multiParams[6],null);
                reportHelper.reportQueryState(ReportHelper.INST,multiParams[7],null);
                reportHelper.reportQueryState(ReportHelper.STATUS,multiParams[8],null);
                reportHelper.reportQueryState(ReportHelper.ADDRESS,singleParams[1],null);
                reportHelper.reportQueryState(ReportHelper.OFFICE,singleParams[2],singleParams[5]);
                reportHelper.reportQueryState(ReportHelper.ENTRYTYPE,singleParams[3], null);
                reportHelper.reportQueryState(ReportHelper.TEXT,param2,null);

                break;
            case Constant.TITLE.TITLE_SELECTPERSON:
                url += Constant.URL.URL_QNAME;
                params.put("pageNum", mPageNum + "");
                params.put("name", mSearchStr);
                break;
            case Constant.TITLE.TITLE_KINSHIPRESULT:
                url += Constant.URL.URL_QKUNSHIPPERSON;
                params.put("pageNum", mPageNum + "");
                params.put("personid",param1 == null ? "" : param1);
                if (StringUtil.isNotNull(param2)) {
                    param2 =  param2.substring(0,param2.length()-1);
                }else {
                    param2 = "";
                }
                params.put("relationIds",param2);

                reportHelper.reportQueryState(ReportHelper.PERSONINFO,param1,null);
                reportHelper.reportQueryState(ReportHelper.KINSHIP,param2,null);
                break;
            case Constant.TITLE.TITLE_ASSOCRESULT:
                url += Constant.URL.URL_QASSOCPERSON;
                params.put("pageNum", mPageNum + "");
                params.put("personid",param1 == null ? "" : param1);
                params.put("relationIds",param2 == null ? "" : param2);

                reportHelper.reportQueryState(ReportHelper.PERSONINFO,param1,null);
                reportHelper.reportQueryState(ReportHelper.ASSOC,param1,param2);
                break;
        }

        Log.d(TAG, "requestParams: " + params);

        NetRequest.getFormRequest(url, params, new NetRequest.DataCallBack() {
            @Override
            public void requestSuccess(String result) throws Exception {
                Log.d(TAG, "json返回数据：" + result);

                PageBean<QBiogCustom> pageBean = new Gson().fromJson(result, new TypeToken<PageBean<QBiogCustom>>() {
                }.getType());
                mResults.clear();
                mResults.addAll(pageBean.getRecordList());
                mTotalPage = pageBean.getTotalPage();

                Message message = Message.obtain();
                message.what = mode;
                Bundle bundle = new Bundle();
                bundle.putInt("pageNum", mPageNum);
                bundle.putInt("totalPage", pageBean.getTotalPage());
                bundle.putInt("totalCount", pageBean.getTotalCount());
                message.setData(bundle);
                handler.sendMessage(message);
            }

            @Override
            public void requestFailure(Request request, IOException e) {
                mLoadingDialog.dismiss();
                ToastUtil.showShort(mContext, "请求错误！");
            }
        });
    }
}
